package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.common.result.Result;
import com.sxpi.convert.WorksConvert;
import com.sxpi.mapper.*;
import com.sxpi.model.entity.*;
import com.sxpi.model.vo.WorksVo;
import com.sxpi.service.WorksService;
import com.sxpi.utils.FileUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class WorksServiceImpl extends ServiceImpl<WorksMapper, Works> implements WorksService {
    @Resource
    private WorksMapper worksMapper;
    @Resource
    private WorksImageMapper worksImageMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private CostumesMapper costumesMapper;
    @Resource
    private CostumeImagesMapper costumeImagesMapper;
    @Resource
    private LikesMapper likesMapper;
    @Resource
    private BookingsMapper bookingsMapper;
    ///上传文件路径
    @Value("${uploadFile.path}")
    private String uploadDir;
    @Override
    public List<WorksVo> getAllWorks(Long worksId,Long userId) {
        List<WorksVo> result = new ArrayList<>();

        // 如果worksId为null，查询所有作品
        if (worksId == null) {
            List<Works> allWorks = worksMapper.selectList(null);
            for (Works works : allWorks) {
                // 查询所有作品时不包含userCostumes信息
                result.add(getWorkDetail(works, false,null));
            }
            return result;
        }

        // 如果worksId不为null，查询单个作品
        Works works = worksMapper.selectById(worksId);
        if (Objects.isNull(works)) {
            return null;
        }
        // 查询单个作品时包含userCostumes信息
        result.add(getWorkDetail(works, true,userId));
        return result;
    }

    //新增作品
    @Override
    public Boolean addWorks(List<MultipartFile> files, Long userId, String title, String description) {
        log.info("files:{}", files);

        Works works = new Works();

        works.setUserId(userId);
        works.setTitle(title);
        works.setDescription(description);
        int insert = worksMapper.insert(works);
        Long workId = works.getId();
        log.info("workId:{}", workId);
        files.forEach(file -> {
            String url = FileUtil.uploadFile(file, uploadDir);
            WorkImages workImages = new WorkImages();
            workImages.setWorkId(workId.toString());
            workImages.setImageUrl(url);
            worksImageMapper.insert(workImages);
        });

        return insert > 0;
    }

    // 修改获取作品详情的方法，添加includeUserCostumes参数
    private WorksVo getWorkDetail(Works works, boolean includeUserCostumes,Long userId) {
        WorksVo worksVo = WorksConvert.INSTANCE.convertEntityToVo(works);

        // 查询作品相关的图片信息
        LambdaQueryWrapper<WorkImages> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkImages::getWorkId, works.getId());
        List<WorkImages> worksImages = worksImageMapper.selectList(queryWrapper);
        log.info("worksImages: {}", worksImages);
        worksImages.stream().forEach(worksImage -> {
            if (worksImage.getIsMain() == 1){
             worksVo.setIsMain(worksImage.getImageUrl());
            }
        });
        List<String> imageUrls = worksImages.stream()
                .map(WorkImages::getImageUrl)
                .toList();
        worksVo.setWorksImage(imageUrls);

        // 查询作品关联的用户基本信息
        Users user = usersMapper.selectById(works.getUserId());
        if (user != null) {
            worksVo.setNickName(user.getNickname());
            worksVo.setAvatarUrl(user.getAvatarUrl());
            LambdaQueryWrapper<Likes> likesQueryWrapper = new LambdaQueryWrapper<Likes>()
                    .eq(Likes::getUserId, userId)
                    .eq(Likes::getWorkId, works.getId());
            boolean isLiked = likesMapper.exists(likesQueryWrapper);
//                System.out.println("isLiked是"+isLiked);
            worksVo.setIsLike(isLiked? 1 : 0);
            Long l = likesMapper.selectCount(new LambdaQueryWrapper<Likes>().eq(Likes::getWorkId, works.getId()));
            worksVo.setLikesCount(l);



            // 只有在includeUserCostumes为true时才查询和设置userCostumes信息
            if (includeUserCostumes) {
                Map<String, Object> userCostume = new HashMap<>();

                LambdaQueryWrapper<Bookings> bookingsWrapper = new LambdaQueryWrapper<>();
                bookingsWrapper.eq(Bookings::getUserId, user.getId());
                List<Bookings> bookings = bookingsMapper.selectList(bookingsWrapper);

                List<Map<String, Object>> costumeInfoList = new ArrayList<>();
                for (Bookings booking : bookings) {
                    Costumes costume = costumesMapper.selectById(booking.getCostumeId());
                    if (costume != null) {
                        LambdaQueryWrapper<CostumeImages> imageWrapper = new LambdaQueryWrapper<>();
                        imageWrapper.eq(CostumeImages::getCostumeId, booking.getCostumeId())
                                .eq(CostumeImages::getIsMain, 1);
                        CostumeImages mainImage = costumeImagesMapper.selectOne(imageWrapper);

                        Map<String, Object> costumeInfo = new HashMap<>();

                        costumeInfo.put("costumeId", costume.getId());
                        costumeInfo.put("costumeName", costume.getName());
                        costumeInfo.put("mainImage", mainImage != null ? mainImage.getUrl() : null);
                        costumeInfoList.add(costumeInfo);
                    }
                }
                userCostume.put("costumeInfo", costumeInfoList);

                List<Map<String, Object>> userCostumes = new ArrayList<>();
                userCostumes.add(userCostume);

                worksVo.setUserCostumes(userCostumes);
            }
        }

        return worksVo;
    }
}